package com.muqi.app.qlearn.login;

import static nl.qbusict.cupboard.CupboardFactory.cupboard;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.muqi.app.im.qmain.EMApplication;
import com.muqi.app.im.qmain.EMHelper;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.project.application.ExitApplication;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.CustomerUtil;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.fragments.TabMine;
import com.muqi.app.qlearn.modles.ChildInfo;
import com.muqi.app.qlearn.modles.UserInfo;
import com.muqi.app.qlearn.student.BaseFragmentActivity;
import com.muqi.app.qlearn.student.MenuActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.AddChildActivity;
import com.muqi.app.sharepreference.SharePreferenceUtil;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.db.CupboardSQLiteOpenHelper;

public class LoginActivity extends BaseFragmentActivity implements OnClickListener {
	/** 用户账号输入框 */
	private EditText username;
	/** 用户密码输入框 */          
	private EditText password;
	/** 用户账号 */
	private String loginName;
	/** 用户密码 */
	private String loginPassword;
	private Button btn_login;
	private ImageButton clear_pwd;
	private ImageButton clear_number;
	private SharePreferenceUtil loginSpUtil;
	public static LoginActivity instance;
	private CupboardSQLiteOpenHelper dbHelper;
   	private SQLiteDatabase sqlDb;
   	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_login);
		if(EMHelper.getInstance().isLoggedIn()){
			EMHelper.getInstance().logout(false,null);
			ShowToast.showShort(mContext, R.string.connect_conflict);
		}
	}

	@Override
	protected void onInit() {
		instance = this;
		username = (EditText) findViewById(R.id.login_username);
		password = (EditText) findViewById(R.id.login_password);
		btn_login = (Button) findViewById(R.id.btn_login);
		clear_number = (ImageButton) findViewById(R.id.clear_number);
		clear_pwd = (ImageButton) findViewById(R.id.clear_pwd);
		clear_number.setOnClickListener(this);
		clear_pwd.setOnClickListener(this);
		btn_login.setOnClickListener(this);
	}

	@Override
	protected void onData() {
		/** 检查是否保存了密码 ,有则取数据 */
		loginSpUtil = new SharePreferenceUtil(this, MContants.LoginPwd);
		if (!TextUtils.isEmpty(loginSpUtil.getUserName()) && !TextUtils.isEmpty(loginSpUtil.getPassword())) {
			username.setText(loginSpUtil.getUserName());
			username.setSelection(loginSpUtil.getUserName().length());
			password.setText(loginSpUtil.getPassword());
		}
		
		dbHelper = new CupboardSQLiteOpenHelper(this);
		sqlDb = dbHelper.getWritableDatabase();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			loginName = username.getText().toString().trim();
			username.setSelection(loginName.length());
			loginPassword = password.getText().toString().trim();
			loginSpUtil.setUserName(loginName);
			loginSpUtil.setPassword(loginPassword);
			if (checkInput()) {
				userLogin(loginName, loginPassword);
			}
			break;
		case R.id.clear_number:
			username.setText("");
			break;
		case R.id.clear_pwd:
			password.setText("");
			break;
		default:
			break;
		}
	}
	
	/**
	 * 调用sdk登陆方法登陆聊天服务器
	 */
	private void loginEMChat(final UserInfo userInfos){
		showProgressWithState("正在登录...");
		EMChatManager.getInstance().login(userInfos.im_user_id, "qlearn!@#qaz",new EMCallBack() {
			@Override
			public void onSuccess() {
				runOnUiThread(new Runnable() {
					public void run() {
						// 登陆成功，保存用户名
						EMHelper.getInstance().setCurrentUserName(userInfos.im_user_id);
						// 注册群组和联系人监听
						EMHelper.getInstance().registerGroupAndContactListener();
						// 第一次登录或者之前logout后再登录，加载所有本地群和回话
						EMGroupManager.getInstance().loadAllGroups();
						EMChatManager.getInstance().loadAllConversations();
						// 更新当前用户的nickname 此方法的作用是在ios离线推送时能够显示用户nick
						boolean updatenick = EMChatManager.getInstance().updateCurrentUserNick(EMApplication.currentUserNick.trim());
						if (!updatenick) {
							Log.e("LoginActivity","update current user nick fail");
						}
						EMHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
						EMHelper.getInstance().getUserProfileManager().setCurrentUserAvatar(userInfos.avatarInfo.fileurl_01);
						EMHelper.getInstance().getUserProfileManager().setCurrentUserNick(userInfos.name);
						showSuccessWithState();
						if(MenuActivity.instance == null){
							startActivity(MenuActivity.class);
						}else{
							Intent intent = new Intent();
							intent.setAction(TabMine.BroadAction);
							sendBroadcast(intent);
						}
						LoginActivity.this.finish();
					}
				});
			}

			@Override
			public void onProgress(int progress, String status) {
				
			}

			@Override
			public void onError(final int code, final String message) {
				runOnUiThread(new Runnable() {
					public void run() {
						showErrorWithState();
						ShowToast.showShort(mContext, "EM_Login_Err:"+message);
					}
				});
			}
		});
	}

	/**
	 * 登录接口
	 */
	private void userLogin(String mobile, String password) {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			btn_login.setEnabled(false);
			HashMap<String, Object> sendMap = new HashMap<String, Object>();
			sendMap.put("mobile", mobile);
			sendMap.put("password", password);
			String requestUrl = ParamsUtils.buildParams(NetWorkApi.Login_Api, sendMap);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {
				
				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode, String request, String result) {
					if(resuleCode == RESULTCODE.SUCCESS){
						try {
							JSONObject resultAllata = new JSONObject(result);
							loginSeviceOk(UserInfo.fromJson(resultAllata.getJSONObject("data")));
						} catch (Exception e) {
							showToast("数据解析失败");
							return ;
						}
					}else{
						
						notLogin(result);
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}
	
	private void loginSeviceOk(UserInfo getInfo){
		btn_login.setEnabled(true);
		if(getInfo != null){
			mSpUtil.setToken(getInfo.token);
			mSpUtil.setUserId(getInfo.id);
			mSpUtil.setUserName(getInfo.name);
			mSpUtil.setUserType(getInfo.user_type);
			CustomerUtil.saveUserInfo(this, getInfo);
			if(!mSpUtil.getUserType().contains(MContants.LOGIN_AS_TEACHER)){
				if(mSpUtil.getUserType().equals(MContants.LOGIN_AS_PARENTS)){
					if(getInfo.parentOwnStudent!=null && getInfo.parentOwnStudent.size()>0){
						mSpUtil.setCurrentChildId(getInfo.parentOwnStudent.get(0).studentInfo.id);//默认第一个孩子
						mSpUtil.setClassName(getInfo.parentOwnStudent.get(0).classInfo.name);
						mSpUtil.setChildClassId(getInfo.parentOwnStudent.get(0).classInfo.class_manager_id);
						mSpUtil.setChildGradeId(getInfo.parentOwnStudent.get(0).classInfo.get_gradeInof.id);
						mSpUtil.setChildSchoolId(getInfo.parentOwnStudent.get(0).classInfo.schoolInfo.id);
						mSpUtil.setSchoolName(getInfo.parentOwnStudent.get(0).classInfo.schoolInfo.name);
						mSpUtil.setChildName(getInfo.parentOwnStudent.get(0).studentInfo.name);	
						mSpUtil.setCurrentIm(getInfo.parentOwnStudent.get(0).studentInfo.im_user_id);
						if(getInfo.parentOwnStudent.get(0).studentInfo.avatarInfo!=null){
							mSpUtil.setCurrentAva(getInfo.parentOwnStudent.get(0).studentInfo.avatarInfo.fileurl_02);
						}
						cupboard().withDatabase(sqlDb).delete(ChildBean.class, "_id < ?", "10000");// clear old datas
						for(ChildInfo child: getInfo.parentOwnStudent){
							ChildBean dbChild = new ChildBean();
							dbChild.parent_id = mSpUtil.getUserId();
							dbChild.child_id = child.studentInfo.id;
							dbChild.id_code = "";
							dbChild.im_user_id = child.studentInfo.im_user_id;
							dbChild.name = child.studentInfo.name;
							dbChild.nickname = child.studentInfo.nickname;
							dbChild.mobile = child.studentInfo.mobile;
							
							dbChild.class_id = child.classInfo.class_manager_id;
							dbChild.class_name = child.classInfo.name;
							
							dbChild.grade_id = child.classInfo.get_gradeInof.id;
							dbChild.grade_name = child.classInfo.get_gradeInof.name;
							
							dbChild.school_id = child.classInfo.schoolInfo.id;
							dbChild.school_name = child.classInfo.schoolInfo.name;
							
							dbChild.avatar_00 = child.studentInfo.avatarInfo.fileurl_00;
							dbChild.avatar_01 = child.studentInfo.avatarInfo.fileurl_01;
							dbChild.avatar_02 = child.studentInfo.avatarInfo.fileurl_02;
							dbChild.avatar_03 = child.studentInfo.avatarInfo.fileurl_03;
							
							cupboard().withDatabase(sqlDb).put(dbChild);
						}
					}else{
						showToast("还未认领孩子信息,请先绑定孩子再登陆");
						startActivity(AddChildActivity.class);
						return;
					}
				}else{
					mSpUtil.setCurrentChildId(getInfo.id);
					mSpUtil.setChildName(getInfo.name);
					mSpUtil.setCurrentChildSex(getInfo.sex);
					mSpUtil.setCurrentIm(getInfo.im_user_id);
					if(getInfo.avatarInfo!=null){
						mSpUtil.setCurrentAva(getInfo.avatarInfo.fileurl_02);
					}
					
					
				}
				loginHxConfigs(getInfo);
			}else{
				showToast("老师端账号不能再学生端登录");
			}
			
		}else{
			ShowToast.showShort(this, NetWorkApi.RETURN_JSON_FAILED);
		}
	}

	protected void loginHxConfigs(UserInfo userInfos) {
		if(userInfos.im_user_id == null || TextUtils.isEmpty(userInfos.im_user_id)){
			ShowToast.showLong(this, "账户信息异常,未绑定环信用户,请联系后台管理人员");
		}else{
			loginEMChat(userInfos);
			loginSpUtil.setUserName(loginName);
			loginSpUtil.setPassword(loginPassword);
		}
	}

	/**
	 * 登录失败后的回调函数
	 */
	public void notLogin(String msg) {
		ShowToast.showShort(this, msg);
		btn_login.setEnabled(true);
	}
	/**
	 * 检测用户名和密码
	 * 
	 * @return
	 */
	private boolean checkInput() {
		if (TextUtils.isEmpty(loginName)) {
			username.setError(getString(R.string.login_username_empty));
		} else if (TextUtils.isEmpty(loginPassword)) {
			password.setError(getString(R.string.login_password_empty));
		} else {
			return true;
		}
		return false;
	}
	
	public void registAccount(View v){
		startActivity(RegistActivity.class);
		//showToast("请使用测试账号直接登录");
	}
	
	/**
	 * tourist login
	 */
	public void loginAstourist(View v){
		
	}
	
	public void forgotPassword(View v){
		startActivity(ForgetPwdActivity.class);
	}
	
	long mExitTime = 0;

	/**
	 * 按两次退出
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if ((System.currentTimeMillis() - mExitTime) > 2000) {// 两次点击间隔小于2秒退出
				this.finish();
			} else {
				ExitApplication.getInstance().exit(this);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
